package com.explorex.infra.puma.gateway.netty.ws.handler;

import com.explorex.infra.puma.gateway.netty.common.AuthStatusEnum;
import com.explorex.infra.puma.gateway.netty.ws.consts.ChannelConst;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;


/**
 * @author: JacceYang
 * @createTime: 2022/07/14 8:03 下午
 * @description: 心跳探测，空闲链接自动剔除
 */
@Slf4j
@ChannelHandler.Sharable
public class HeartbeatIdleHandler extends IdleStateHandler {


    public HeartbeatIdleHandler(long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) {
        super(readerIdleTime, writerIdleTime, allIdleTime, unit);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        if (evt == IdleStateEvent.ALL_IDLE_STATE_EVENT) {
            log.info("channel is idle for a long time, it's closed by server");
            ctx.channel().writeAndFlush(new CloseWebSocketFrame(3101, "idle"));
            ctx.channel().close();
        }

        if (!AuthStatusEnum.AUTHED.toString().equals(ctx.channel().attr(ChannelConst.AUTH_STATUS_KEY).get())) {
            log.info("channel is unAuth for a long time, it's closed by server");
            ctx.channel().writeAndFlush(new CloseWebSocketFrame(3100, "unAuth"));
            ctx.channel().close();
        }
    }
}
